﻿using Dapper;
using Microsoft.AspNetCore.Http;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Helpers;
using PersonalWebsite.Core.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PersonalWebsite.Application.Queries.Website
{
    public record GetTgaGameVO
    {
        public int Id { get; init; }
        public string Name { get; init; }
        public string Country { get; init; }
        public string Desc { get; init; }
        public string AwardTime { get; init; }
        public string PublishTime { get; init; }
        public string Cover { get; private set; }
        public string Video { get; init; }

        public void SetInternetImageUrl(IHttpContextAccessor httpContextAccessor)
        {
            if (!string.IsNullOrEmpty(Cover))
            {
                Cover = FileHelper.GetTgaGameFile(httpContextAccessor, Cover);
            }
        }
    }

    public record GetTgaGameQuery : IQuery<ApiResult<List<GetTgaGameVO>>, List<GetTgaGameVO>>
    { }

    internal class GetTgaGameQueryHandler : QueryHandler<GetTgaGameQuery, ApiResult<List<GetTgaGameVO>>, List<GetTgaGameVO>>
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IDBConnectionFactory dBConnectionFactory;

        public GetTgaGameQueryHandler(IHttpContextAccessor httpContextAccessor, IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
        {
            this.httpContextAccessor = httpContextAccessor;
            this.dBConnectionFactory = dBConnectionFactory;
        }

        public override async Task<ApiResult<List<GetTgaGameVO>>> Handle(GetTgaGameQuery request, CancellationToken cancellationToken)
        {
            using var dbConnection = dBConnectionFactory.GetDbConnection();
            string sql = "SELECT * FROM WS_TgaGame";
            var data = await dbConnection.QueryAsync<GetTgaGameVO>(sql);

            var result = new List<GetTgaGameVO>();
            if (data != null && data.Any())
            {
                foreach (var item in data)
                {
                    item.SetInternetImageUrl(httpContextAccessor);
                    result.Add(item);
                }
            }

            return await Task.FromResult(ApiResult<List<GetTgaGameVO>>.Success(result));
        }
    }
}
